package com.gl.emms.whale.app;



import java.util.Timer;
import java.util.TimerTask;

import android.R.integer;
import android.R.string;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.gl.emms.client.android.EMMSEnventListenerReceiver;
import com.gl.emms.client.android.EMMSListenerManager;
import com.gl.emms.client.android.EMMSPushManager;
import com.gl.emms.client.android.OnEMMSMessageListener;
import com.gl.emms.nio.mutual.ServerMessage;
import com.gl.emms.nio.mutual.ReplyBody;
import com.gl.emms.nio.mutual.RequestBody;
import com.gl.emms.whale.R;
import com.gl.emms.whale.db.MessageDB;
import com.gl.emms.whale.ui.LoginActivity;
import com.gl.emms.whale.ui.SplanshActivity;
import com.gl.emms.whale.ui.SystemMsgActivity;
import com.gl.emms.whale.ui.TabActivity;
import com.gl.emms.whale.util.HeartBeatInfoSaveUtil;
import com.gl.emms.whale.util.SystemMsgEntity;
import com.readystatesoftware.viewbadger.BadgeView;

public  abstract  class WhaleMonitorActivity extends Activity implements OnEMMSMessageListener{

	Timer timer;//定时器

	private static final int HELLO_ID = 1;  
	NotificationManager mNotificationManager;  
	Notification mNotification;  


	private ProgressDialog progressDialog; 
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		EMMSListenerManager.registerMessageListener(this,this);
	}

	@Override
	public void finish() {
		super.finish();
		EMMSListenerManager.removeMessageListener(this);
	}
	@Override
	protected void onStart() {
		super.onStart();
	}
	@Override
	public void onRestart() {
		super.onRestart();
		EMMSListenerManager.registerMessageListener(this,this);
	}

	public abstract void initViews();
	/**
	 * 获取版本号
	 * @return 当前应用的版本号
	 */
	public String getVersion() {
		try {
			PackageManager manager = this.getPackageManager();
			PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
			String version = info.versionName;
			return version;
		} catch (Exception e) {
			e.printStackTrace();
			return "null";
		}
	}
	/*
	public void showProgressDialog(String title,String content)
	{
		commonBaseControl.showProgressDialog(title, content);
	}

	public void hideProgressDialog()
	{
		commonBaseControl.hideProgressDialog();
	}
	 */

	public void showProgressDialog(String title,String message)
	{
		if(progressDialog==null)
		{

			progressDialog = ProgressDialog.show(this, title, message, true, false);
		}else if(progressDialog.isShowing())
		{
			progressDialog.setTitle(title);
			progressDialog.setMessage(message);
		}
		progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				// Cancel task.
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					onUserCancel();
				}
				return false;
			}
		});
		progressDialog.show();

	}

	public void hideProgressDialog()
	{
		if(progressDialog!=null&&progressDialog.isShowing())
		{
			progressDialog.dismiss();
		}
	}
	public void onUserCancel()
	{
		hideProgressDialog();
	}
	public void showToask(String hint){
		Toast toast=Toast.makeText(this,hint,Toast.LENGTH_SHORT);
		toast.show();
	}

	public void showNotification(String content){  
		// ① 获取NotificationManager的引用   
		String ns = Context.NOTIFICATION_SERVICE;  
		mNotificationManager = (NotificationManager)this.getSystemService(ns); 

		// ② 初始化Notification  
		int icon_notify = R.drawable.ic_launcher;  
		CharSequence tickerText = "能源管理系统通知";  
		long when = System.currentTimeMillis();  
		mNotification = new Notification(icon_notify,tickerText,when);  
		mNotification.defaults = Notification.DEFAULT_ALL;  
		mNotification.flags |= Notification.FLAG_NO_CLEAR;  
		mNotification.flags |= Notification.FLAG_SHOW_LIGHTS;  
		// ③ 定义notification的消息 和 PendingIntent  
		Context context = this;  
		CharSequence contentTitle ="能源管理系统通知";  
		CharSequence contentText = content;  
		Intent notificationIntent = new Intent(this,TabActivity.class);  
		PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,0 );  
		mNotification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
		mNotificationManager.notify(HELLO_ID,mNotification);  
	}


	//删除通知：
	public void cancelNotification()
	{
		mNotificationManager.cancel(HELLO_ID);    
	}



	@Override
	public void onConnectionSucceed() {//保证同时只有一个实例
		String idip = MyApplication.getUserData().getIdIP();
		String id = MyApplication.getUserData().getId();
		boolean isOnline = MyApplication.getUserData().getIsOnline();
		String user = MyApplication.getUserData().getName();
		EMMSPushManager.requestId(this,idip,id,isOnline,user);

	}
	@Override
	public void onConnectionStatus(boolean  isConnected){}

	@Override
	public void onReplyReceived(ReplyBody reply) {
		
		if(reply.getType().equals("id_response"))
		{
			String idipString = reply.get("idip");
			MyApplication.getUserData().setIdIp(idipString);
			MyApplication.getUserData().setId(reply.get("id"));
			MyApplication.getUserData().setLastversion((reply.get("android_lastversion")));
			showToask("sessionid = "+reply.getReciever()+"  id = "+reply.get("idip"));
			
			//这里存放心跳需要的东西 idip 名字 是否在线
			new HeartBeatInfoSaveUtil(this).setHeartBeatInfo(idipString, MyApplication.getUserData().getIsOnline(), MyApplication.getUserData().getName());
		}
		/*
		if(reply.getType().equals("erro_response"))
		{
			showToask("上位机未准备好");
		}
		if(reply.getType().equals("heartbeat_response"))
		{
			//showToask("上位机心跳");
		}
		 */
	}

	@Override
	public void onMessageReceived(ServerMessage arg0) {
		Log.v("whale", "onMessageReceived");
		/*
		if(arg0.getType().equals("Notify"))
		{
			showNotification(arg0.getContent());
		}
		if(arg0.getType().equals("Message"))
		{
			String msgtitle = arg0.get("title");
			String date = arg0.get("date");// 消息日期
			String msgfrom = arg0.get("from");// 消息来源
			String msgto = arg0.get("to");// 消息来源
			String message = arg0.get("message");// 消息内容
			int img = R.drawable.icon;//消息图片
			int isreaded = 0;// 是否已读
			//MessageDB messageDB = new MessageDB(this);
			//int msgId=messageDB.getMaxId()+1;
			int msgId = 0;
			SystemMsgEntity systemMsgEnity = new SystemMsgEntity(msgId,msgtitle, date, msgfrom,msgto,message,img, isreaded);
			//messageDB.close();
			hasMsg(systemMsgEnity);

		}
		 */
	}
	public void hasMsg(SystemMsgEntity systemMsgEnity) {

	}
	@Override
	public void onRequestReceived(RequestBody requestBody) {}

	@Override
	public   void onNetworkChanged(NetworkInfo info){
		Log.v("whale", "onNetworkChanged");
	};
	/*
	public void onSendHeartBeat()
	{
		EMMSPushManager.requestHeartBeat(this,MyApplication.getUserData().getIdIP(),MyApplication.getUserData().getIsOnline(),MyApplication.getUserData().getName());
	}
	*/
	/*
	public void startTimer(int secends){

		TimerTask task = new TimerTask(){   
			public void run() {
				timerCancle();
				timerStop();
			}   
		};
		timer = new Timer(true);  
		timer.schedule(task,secends*1000);
	}
	public void timerCancle(){
		timer.cancel();
	}
	public void timerStop(){
		Log.v("whale", "timerStop");
	}
	 */
}
